<template>
  <div class="enrollment-card p-4 surface-card border-round-xl shadow-2">
    <div class="flex justify-content-between align-items-center mb-3">
      <div class="text-xl font-bold">{{ enrollment.course_name }}</div>
      <div class="flex gap-2">
        <Button icon="pi pi-eye" class="p-button-rounded p-button-text" @click="showDetails = true" />
        <Button icon="pi pi-pencil" class="p-button-rounded p-button-text p-button-warning" 
          @click="navigateToEdit" v-if="auth.canView('enrollments/edit')" />
        <Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger" 
          @click="confirmDelete" v-if="auth.canView('enrollments/delete')" />
      </div>
    </div>

    <div class="grid">
      <div class="col-12 mb-2">
        <div class="text-500">课程编号</div>
        <div class="text-900">{{ enrollment.course_id }}</div>
      </div>
      <div class="col-12 mb-2">
        <div class="text-500">任课教师</div>
        <div class="text-900">{{ enrollment.teacher_name }}</div>
      </div>
      <div class="col-12 mb-2">
        <div class="text-500">课程时间</div>
        <div class="text-900">
          <div class="flex align-items-center mb-2">
            <i class="pi pi-calendar text-500 mr-2"></i>
            <span class="text-500">开始日期</span>
          </div>
          <div class="text-900 font-medium">{{ formatDate(courseInfo.start_date) }}</div>
          <div class="flex align-items-center mb-2 mt-3">
            <i class="pi pi-calendar text-500 mr-2"></i>
            <span class="text-500">结束日期</span>
          </div>
          <div class="text-900 font-medium">{{ formatDate(courseInfo.end_date) }}</div>
        </div>
      </div>
      <div class="col-12 mb-2" v-if="auth.userRole !== 'student'">
        <div class="text-500">选课人数</div>
        <div class="text-900">
          <Tag :value="enrollment.student_count + '人'" severity="info" />
        </div>
      </div>
      <div class="col-12" v-if="auth.userRole === 'student'">
        <div class="text-500">状态</div>
        <Tag :value="enrollment.status" :severity="getStatusSeverity(enrollment.status)" />
      </div>
    </div>

    <!-- 详情对话框 -->
    <Dialog v-model:visible="showDetails" :header="enrollment.course_name" :modal="true" :style="{ width: '500px' }">
      <div class="grid">
        <div class="col-12 mb-2">
          <div class="text-500">课程编号</div>
          <div class="text-900">{{ enrollment.course_id }}</div>
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">课程名称</div>
          <div class="text-900">{{ enrollment.course_name }}</div>
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">任课教师</div>
          <div class="text-900">{{ enrollment.teacher_name }}</div>
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">教师工号</div>
          <div class="text-900">{{ enrollment.teacher_id }}</div>
        </div>
        <div class="col-12 mb-2" v-if="auth.userRole !== 'student'">
          <div class="text-500">选课人数</div>
          <div class="text-900">{{ enrollment.student_count }}人</div>
        </div>
        <div class="col-12 mb-2" v-if="auth.userRole !== 'student'">
          <div class="text-500">选课学生</div>
          <div class="text-900">
            <div class="flex flex-wrap gap-2">
              <Tag v-for="student in studentNameTags" 
                   :key="student.id" 
                   :value="student.name"
                   severity="info" />
            </div>
          </div>
        </div>
        <div class="col-12 mb-2" v-if="auth.userRole === 'student'">
          <div class="text-500">状态</div>
          <Tag :value="enrollment.status" :severity="getStatusSeverity(enrollment.status)" />
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">创建时间</div>
          <div class="text-900">{{ formatDate(enrollment.created_at) }}</div>
        </div>
        <div class="col-12">
          <div class="text-500">更新时间</div>
          <div class="text-900">{{ formatDate(enrollment.updated_at) }}</div>
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">课程时间</div>
          <div class="text-900">
            <div class="flex align-items-center mb-2">
              <i class="pi pi-calendar text-500 mr-2"></i>
              <span class="text-500">开始日期</span>
            </div>
            <div class="text-900 font-medium">{{ formatDate(courseInfo.start_date) }}</div>
            <div class="flex align-items-center mb-2 mt-3">
              <i class="pi pi-calendar text-500 mr-2"></i>
              <span class="text-500">结束日期</span>
            </div>
            <div class="text-900 font-medium">{{ formatDate(courseInfo.end_date) }}</div>
          </div>
        </div>
      </div>
    </Dialog>

    <!-- 编辑对话框 -->
    <Dialog v-model:visible="showEditDialog" :header="'编辑选课状态'" :modal="true" :style="{ width: '400px' }">
      <div class="grid">
        <div class="col-12 mb-2">
          <div class="text-500">课程名称</div>
          <div class="text-900">{{ enrollment.course_name }}</div>
        </div>
        <div class="col-12 mb-2">
          <div class="text-500">任课教师</div>
          <div class="text-900">{{ enrollment.teacher_name }}</div>
        </div>
        <div class="col-12 mb-3">
          <label for="student_id" class="block text-500 mb-2">选择学生</label>
          <Dropdown id="student_id" 
            v-model="editForm.student_id" 
            :options="studentOptions"
            optionLabel="name"
            optionValue="id"
            placeholder="请选择要修改的学生"
            class="w-full" />
        </div>
        <div class="col-12 mb-3">
          <label for="status" class="block text-500 mb-2">选课状态</label>
          <Dropdown id="status" 
            v-model="editForm.status" 
            :options="statusOptions" 
            optionLabel="label" 
            optionValue="value"
            class="w-full" />
        </div>
      </div>
      <template #footer>
        <Button label="取消" icon="pi pi-times" class="p-button-text" @click="showEditDialog = false" />
        <Button label="保存" icon="pi pi-check" @click="handleEdit" />
      </template>
    </Dialog>

    <!-- 删除确认对话框 -->
    <Dialog v-model:visible="showDeleteConfirm" :header="'确认删除'" :modal="true" :style="{ width: '450px' }">
      <div class="confirmation-content">
        <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
        <div class="flex flex-column">
          <span class="mb-2">确定要删除以下课程的所有选课记录吗？</span>
          <span class="font-bold">{{ enrollment.course_name }}</span>
          <span class="text-sm text-500">（当前选课人数：{{ enrollment.student_count }}人）</span>
        </div>
      </div>
      <template #footer>
        <Button label="取消" icon="pi pi-times" class="p-button-text" @click="showDeleteConfirm = false" />
        <Button label="确定删除" icon="pi pi-check" class="p-button-danger" @click="handleDelete" />
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuth } from 'src/composables/auth';
import { ApiService } from 'src/services/api';

// PrimeVue 组件导入
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import InputText from 'primevue/inputtext';
import Dropdown from 'primevue/dropdown';

const router = useRouter();
const auth = useAuth();
const toast = useToast();

const props = defineProps({
  enrollment: {
    type: Object,
    required: true,
    default: () => ({
      enrollment_id: '',
      course_id: '',
      course_name: '',
      teacher_id: '',
      teacher_name: '未知教师',
      student_count: 0,
      student_ids: [],
      status: '',
      created_at: null,
      updated_at: null
    })
  }
});

const emit = defineEmits(['enrollment-deleted']);

const showDetails = ref(false);
const showDeleteConfirm = ref(false);
const showEditDialog = ref(false);
const editForm = ref({
  student_id: '',
  status: ''
});

// 添加学生姓名缓存
const studentNames = ref({});

const courseInfo = ref({
  start_date: '',
  end_date: ''
});

const formatDate = (date) => {
  if (!date) return '未设置';
  
  try {
    const date = new Date(date);
    return date.toLocaleDateString('zh-CN');
  } catch (error) {
    return date;
  }
};

const statusOptions = [
  { label: '已选课', value: 'enrolled' },
  { label: '已退课', value: 'unenrolled' }
];

const getStatusSeverity = (status) => {
  switch (status) {
    case 'enrolled':
      return 'success';
    case 'unenrolled':
      return 'danger';
    default:
      return 'info';
  }
};

const studentOptions = ref([]);

const loadStudentOptions = async () => {
  try {
    // 获取该课程的所有选课记录
    const response = await ApiService.get(`enrollments/index/course_name/${encodeURIComponent(props.enrollment.course_name)}`);
    if (response.data && response.data.records) {
      // 获取所有学生的信息并构建选项
      const options = await Promise.all(
        response.data.records.map(async (record) => {
          const studentName = await getStudentName(record.student_id);
          return {
            id: record.student_id,
            name: `${studentName} (${record.student_id})`,
            enrollment_id: record.enrollment_id,
            enrollment_date: record.enrollment_date
          };
        })
      );
      studentOptions.value = options;
    }
  } catch (error) {
    console.error('加载学生列表失败:', error);
    toast.add({
      severity: 'error',
      summary: '错误',
      detail: '加载学生列表失败',
      life: 3000
    });
  }
};

const navigateToEdit = async () => {
  editForm.value = {
    student_id: '',
    status: props.enrollment.status
  };
  await loadStudentOptions();
  showEditDialog.value = true;
};

const confirmDelete = () => {
  showDeleteConfirm.value = true;
};

const handleDelete = async () => {
  try {
    // 获取该课程的所有选课记录ID
    const response = await ApiService.get(`enrollments/index/course_name/${encodeURIComponent(props.enrollment.course_name)}`);
    if (response.data && response.data.records) {
      const enrollmentIds = response.data.records.map(record => record.enrollment_id).join(',');
      // 批量删除所有选课记录
      await ApiService.get(`enrollments/delete/${enrollmentIds}`);
      showDeleteConfirm.value = false;
      // 立即发送删除成功事件
      emit('enrollment-deleted', { 
        success: true, 
        courseName: props.enrollment.course_name,
        immediate: true // 添加标记表示需要立即刷新
      });
      // 显示成功提示
      toast.add({ 
        severity: 'success', 
        summary: '成功', 
        detail: `已删除课程"${props.enrollment.course_name}"的所有选课记录`, 
        life: 3000 
      });
    }
  } catch (error) {
    console.error('删除失败:', error);
    showDeleteConfirm.value = false;
    toast.add({ 
      severity: 'error', 
      summary: '错误', 
      detail: `删除课程"${props.enrollment.course_name}"的选课记录失败`, 
      life: 3000 
    });
    emit('enrollment-deleted', { success: false, error });
  }
};

const handleEdit = async () => {
  try {
    if (!editForm.value.student_id) {
      toast.add({ 
        severity: 'error', 
        summary: '错误', 
        detail: '请选择学生', 
        life: 3000 
      });
      return;
    }

    // 从studentOptions中找到选中的学生信息
    const selectedStudent = studentOptions.value.find(
      student => student.id === editForm.value.student_id
    );

    if (!selectedStudent) {
      toast.add({ 
        severity: 'error', 
        summary: '错误', 
        detail: '未找到选中学生的选课记录', 
        life: 3000 
      });
      return;
    }

    // 更新选课记录
    await ApiService.post(`enrollments/edit/${selectedStudent.enrollment_id}`, {
      status: editForm.value.status,
      enrollment_date: selectedStudent.enrollment_date
    });

    showEditDialog.value = false;
    toast.add({ 
      severity: 'success', 
      summary: '成功', 
      detail: `${selectedStudent.name} 的选课状态更新成功`, 
      life: 3000 
    });
    
    // 通知父组件刷新数据
    emit('enrollment-deleted', { 
      success: true, 
      courseName: props.enrollment.course_name,
      immediate: true
    });
  } catch (error) {
    console.error('更新失败:', error);
    toast.add({ 
      severity: 'error', 
      summary: '错误', 
      detail: '更新选课状态失败', 
      life: 3000 
    });
  }
};

// 添加获取学生姓名的方法
const getStudentName = async (studentId) => {
    if (!studentNames.value[studentId]) {
        try {
            const response = await ApiService.get(`users/view/${studentId}`);
            if (response.data) {
                studentNames.value[studentId] = response.data.name || studentId;
            } else {
                studentNames.value[studentId] = studentId;
            }
        } catch (error) {
            console.error('获取学生姓名失败:', error);
            studentNames.value[studentId] = studentId;
        }
    }
    return studentNames.value[studentId] || studentId;
};

// 添加获取课程信息的方法
const getCourseInfo = async (courseId) => {
  try {
    const response = await ApiService.get(`courses/view/${courseId}`);
    if (response.data) {
      courseInfo.value = {
        start_date: response.data.start_date,
        end_date: response.data.end_date
      };
    }
  } catch (error) {
    console.error('获取课程信息失败:', error);
  }
};

// 修改 onMounted 钩子
onMounted(async () => {
  // 加载学生姓名
  if (props.enrollment.student_ids && props.enrollment.student_ids.length) {
    for (const studentId of props.enrollment.student_ids) {
      await getStudentName(studentId);
    }
  }
  // 加载课程信息
  if (props.enrollment.course_id) {
    await getCourseInfo(props.enrollment.course_id);
  }
});

// 添加计算属性来获取学生姓名列表
const studentNameTags = computed(() => {
    return props.enrollment.student_ids.map(studentId => ({
        id: studentId,
        name: studentNames.value[studentId] || studentId
    }));
});
</script>

<style scoped>
.enrollment-card {
  transition: transform 0.2s, box-shadow 0.2s;
}

.enrollment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.confirmation-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
}
</style> 